package com.ruoyi.netty.handle;

import com.ruoyi.netty.enums.TerminalTypeEnum;
import com.ruoyi.netty.utils.SocketChannelUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SocketHandler extends ChannelInboundHandlerAdapter {

    /**
     * 连接
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        log.info("客户端连接：{}", ctx.channel().id().asShortText());
        SocketChannelUtil.addChannelCtx(ctx.channel().id().asShortText(), TerminalTypeEnum.COMMON.getCode(), ctx);
    }

    /**
     * 断开
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        log.info("客户端断开：{}", ctx.channel().id().asShortText());
        SocketChannelUtil.removeChannelCtx(ctx.channel().id().asShortText(), TerminalTypeEnum.COMMON.getCode());
    }

    /**
     * 异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("客户端异常：{}", ctx.channel().id().asShortText(), cause);
        ctx.channel().close();
        SocketChannelUtil.removeChannelCtx(ctx.channel().id().asShortText(), TerminalTypeEnum.COMMON.getCode());
    }

    /**
     * 收发
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 接收消息
        byte[] data = (byte[]) msg;

        log.info("收到消息：{}", new String(data));

        // 获取通道
        ChannelHandlerContext channelCtx = SocketChannelUtil.getChannelCtx(ctx.channel().id().asShortText(), TerminalTypeEnum.COMMON.getCode());

        // 发送消息
        if (channelCtx != null) {
            channelCtx.channel().writeAndFlush(data);
        }
    }

}
